
package com.gitee.jmash.rbac.mapper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import com.crenjoy.proto.mapper.BeanMapper;
import com.crenjoy.proto.mapper.ProtoMapper;
import com.gitee.jmash.core.orm.DtoPage;
import com.gitee.jmash.core.orm.DtoTotal;
import com.gitee.jmash.rbac.entity.DeptEntity;
import jmash.rbac.protobuf.DeptCreateReq;
import jmash.rbac.protobuf.DeptList;
import jmash.rbac.protobuf.DeptModel;
import jmash.rbac.protobuf.DeptModel.Builder;
import jmash.rbac.protobuf.DeptPage;

/**
 * DeptMapper.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
@Mapper
public interface DeptMapper extends BeanMapper, ProtoMapper {

  DeptMapper INSTANCE = Mappers.getMapper(DeptMapper.class);

  default DeptList listTreeDept(List<DeptEntity> list) {
    // 全部部门信息.
    Map<UUID, Builder> map = list.stream().collect(Collectors.toMap(DeptEntity::getDeptId,
        obj -> DeptMapper.INSTANCE.model(obj).toBuilder(), (oldValue, newValue) -> oldValue));
    // 倒序添加孩子
    List<DeptEntity> reverseList = new ArrayList<>(list);
    Collections.reverse(reverseList);

    // 数据建立父子关系
    List<UUID> roots = new ArrayList<>();
    for (DeptEntity dept : reverseList) {
      DeptModel.Builder model = map.get(dept.getDeptId());
      DeptModel.Builder parent = map.get(dept.getParentId());
      if (parent == null) {
        roots.add(dept.getDeptId());
      } else {
        parent.addChildren(0, model);
      }
    }
    // 根列表
    DeptList.Builder builder = DeptList.newBuilder();
    for (UUID root : roots) {
      builder.addResults(0, map.get(root));
    }
    return builder.build();
  }

  List<DeptModel> listDept(List<DeptEntity> list);

  DeptPage pageDept(DtoPage<DeptEntity, DtoTotal> page);

  DeptModel model(DeptEntity entity);

  DeptEntity create(DeptCreateReq req);

  DeptEntity clone(DeptEntity entity);


}
